package com.example.actuator.service;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalTime;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class ThreadPoolTest {
    private final AtomicInteger runTaskNums = new AtomicInteger(0);

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            1, 1, 30 * 1000L, TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(2),
            Executors.defaultThreadFactory(),
            (((r, executor) -> {
                try {
                    log.info(LocalTime.now() + ":阻塞任务提交，队列长度为：{}，当前执行任务数为{}", executor.getQueue().size(), runTaskNums.get());
                    // 阻塞任务提交
                    executor.getQueue().put(r);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }))
    );

    public static void main(String[] args) {
        ThreadPoolTest threadPoolTest = new ThreadPoolTest();
        for (int i = 0; i < 10; i++) {
            threadPoolTest.run(i);
        }
    }

    private void run(int i) {
        threadPoolExecutor.submit(() -> {
            try {
                runTaskNums.incrementAndGet();
                log.info(LocalTime.now() + "：执行任务" + i + "开始");
                Thread.sleep(10000);
                log.info(LocalTime.now() + "：执行任务" + i + "结束");
                runTaskNums.decrementAndGet();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
